/* 
 * Cashbox is the legal property of its developers, whose names are listed in the copyright file included
 * with this source distribution.
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation; either version 2 of the License,
 * or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
 * Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not,
 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#import "CBInterfaceController.h"
#import "CBControllerProtocol.h"

#import "CBPreferenceWindowController.h"
#import "CBSetupAssistantWindowController.h"
#import "CBMainWindowController.h"

#import "CBAccount.h"

#import <Cashbox/CBDataControllerProtocol.h>

@implementation CBInterfaceController

- (void)dealloc {
	[mainWindowController release];
	[preferenceWindowController release];
	
	[super dealloc];
}

- (void)controllerDidLoad {
	
	NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
	[request setEntity:[CBAccount entity]];
	[request setFetchLimit:1];
	NSArray *results = [[[cashbox dataController] managedObjectContext] executeFetchRequest:request error:NULL];
	
	if ([results count]) {
		[self showMainWindow:nil];
	} else {
		[CBSetupAssistantWindowController runSetupAssistantWithDelegate:self
														 didEndSelector:@selector(finishedSetupAssistant:)
													 didDismissSelector:@selector(dismissedSetupAssistant:)];		
	}
	
}

- (void)finishedSetupAssistant:(id)sender {
	[self showMainWindow:nil];
}

- (void)dismissedSetupAssistant:(id)sender {
	[[[cashbox dataController] managedObjectContext] reset];
	[NSApp terminate:nil];
}

- (void)controllerWillClose {
}

- (CBMainWindowController *)mainWindowController {
	if (!mainWindowController) {
		// create the window and also set the autosave name
		mainWindowController = [[CBMainWindowController alloc] init];
		// using setAutosaveName and NOT setFrameAutosaveName so that
		// autosave information is passed on to other controllers
		[mainWindowController setAutosaveName:@"Main Window"];
	}
	return mainWindowController;
}

- (NSWindow *)mainWindow {
	return [[self mainWindowController] window];
}

- (IBAction)showMainWindow:(id)sender {
	[[self mainWindow] makeKeyAndOrderFront:nil];
}

- (IBAction)showRegistration:(id)sender {
#warning implement
}

- (IBAction)showPreferences:(id)sender {
	[CBPreferenceWindowController openPreferenceWindow:nil];
}

@end
